package com.bibrApp.difu.actvity.tibi_mvp;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bibrApp.difu.DfApp;
import com.bibrApp.difu.R;
import com.bibrApp.difu.actvity.login_mvp.LoginActivity;
import com.bibrApp.difu.base.BasePermissionActivity;
import com.bibrApp.difu.dialog.AddressPopup;
import com.bibrApp.difu.dialog.MyCustomDialog;
import com.bibrApp.difu.dialog.OneBtnDialog;
import com.bibrApp.difu.fragment.cloudwallet_mvp.CloudWalletBean;
import com.bibrApp.difu.utils.BigdecimalUtils;
import com.bibrApp.difu.utils.IntentUtil;
import com.bibrApp.difu.utils.ToastUtils;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;

public class TibiActivity extends BasePermissionActivity<TibiPresenter> implements ITibiView {


    @BindView(R.id.tv_keyong)
    TextView tvPawnMonry;
    @BindView(R.id.tv_wallet)
    TextView tvWallet;
    @BindView(R.id.tv_no)
    TextView tvNo;
    /*@BindView(R.id.tv_addr)
    EditText tvAddr;*/
    @BindView(R.id.tv_address)
    TextView tvAddr;
    @BindView(R.id.edittext)
    EditText editText;
    @BindView(R.id.tv_address_description)
    TextView tvAddressDescription;
    @BindView(R.id.fl_expand_address)
    View flExpand;
    private CloudWalletBean bean;
    private DfApp app;
    private Context mContext;
    private int typeWallet;//0：云钱包，1：多签钱包 2：合约钱包
    private MyCustomDialog.Builder mDialog;
    private CountTimer timer;
    class CountTimer extends CountDownTimer {

        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            getVerifyCodeTV.setEnabled(true);
            getVerifyCodeTV.setClickable(true);
            getVerifyCodeTV.setText("点击获取");
            getVerifyCodeTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    presenter.getCode(app.getmData().getCenterUserMain().getPhone());
                }
            });
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            getVerifyCodeTV.setText((millisUntilFinished / 1000) + "S" + "重新获取");
        }
    }

    @Override
    protected void initPresenter() {
        presenter = new TibiPresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tibi;
    }


    @Override
    public void error(String msg) {
        showToast(msg);
    }

    @Override
    public void success(String msg) {
        showToast(msg);
        finish();
    }

    private List<AddrBean> mAddressData = new ArrayList<>();
    private AddrBean mCurrentAddress;

    @Override
    public void onAddrResult(List<AddrBean> datas) {
        /*if (list != null && list.size() > 0) {
            tvAddr.setText(list.get(0).address);
        }*/
        mAddressData.clear();
        mAddressData.addAll(datas);
        if (mAddressData.size() < 1) {
            tvAddr.setText("请选择提币地址");
            tvAddressDescription.setText("");
        } else {
            mCurrentAddress = mAddressData.get(datas.size() - 1);
            tvAddr.setText(mCurrentAddress.getAddress());
            tvAddressDescription.setText(mCurrentAddress.getRemark());
//            textChange();
        }
    }

    @Override
    public void successOfAddAddress(String msg) {
        ToastUtils.ShowToast(mContext, msg);
        presenter.getAddrData(app.getUserId(), bean.getCoinEunit());
    }

    //获取验证码成功
    @Override
    public void successOfCode(String msg) {
        if (timer == null) {
            timer = new CountTimer(60000, 1000);
        }
        timer.start();
        getVerifyCodeTV.setEnabled(false);
        getVerifyCodeTV.setClickable(false);
    }

    @Override
    public void initView() {

        app = (DfApp) getApplication();
        mContext = this;
        Intent intent = getIntent();
        bean = (CloudWalletBean) intent.getSerializableExtra("bean");
        typeWallet = intent.getIntExtra("type", 0);

        String wallet = intent.getStringExtra("wallet");
        tvWallet.setText(wallet);
        if (typeWallet == 0) {
            tvNo.setVisibility(View.GONE);
        } else {
            tvNo.setVisibility(View.VISIBLE);
        }
        tvNo.setText(bean.getCoinId());


        if (bean != null) {
            if (bean.getCoinEunit().equals("BTC")) {
                tvPawnMonry.setText("可用余额" + BigdecimalUtils.getBigDecimalPrice(bean.getHotMoney(), 8) + bean.getCoinEunit());
            } else {
                tvPawnMonry.setText("可用余额" + BigdecimalUtils.getBigDecimalPrice(bean.getHotMoney(), 2) + bean.getCoinEunit());
            }
        }


        presenter.getAddrData(app.getUserId(), bean.getCoinEunit());


    }

    AddressPopup mAddressPopup;

    @OnClick(R.id.fl_expand_address)
    public void showPopAddress() {
        if (mAddressPopup == null) {
            mAddressPopup = new AddressPopup(mContext, new AddressPopup.OnPopupCallBack() {
                @Override
                public void onItemClick(AddrBean data) {
                        mCurrentAddress = data;
                        tvAddr.setText(data.getAddress());
                        tvAddressDescription.setText(data.getRemark());
                }

                @Override
                public void onDeleteClick(AddrBean data) {


                }
            });
            mAddressPopup.setAddressData(mAddressData);
            mAddressPopup.showBottom(flExpand);
        }
        mAddressPopup.showBottom(flExpand);
    }

    @OnClick(R.id.tv_all)
    public void allClick() {
        if (bean.getCoinEunit().equals("BTC")) {
            editText.setText(String.valueOf(BigdecimalUtils.getBigDecimalPrice(bean.getHotMoney(), 8)));
        } else {
            editText.setText(String.valueOf(BigdecimalUtils.getBigDecimalPrice(bean.getHotMoney(), 2)));
        }
    }

    @OnClick(R.id.bt_back)
    public void backClick() {
        onBackPressed();
    }

    @OnClick(R.id.add_address_tv)
    public void onClickAddAddress() {
        showAddAddressDialog();
    }

    private OneBtnDialog.Builder builder;
    private int REQUEST_CODE = 0x1001;

    private void showAddAddressDialog() {
        if (builder == null) {
            builder = new OneBtnDialog.Builder(mContext, R.style.OneBtnDialog);
            builder.setTitle("新增提币地址");
            builder.setTitleIsVisible(true);
            builder.setRightBtnStr("确认添加");
            builder.setEtIsVisible(true);
            builder.setEtOneIsVisible(true);
            builder.setButtonClick(new OneBtnDialog.OnButtonClick() {
                @Override
                public void onOk(String address, String remark) {
                    if (TextUtils.isEmpty(address)) {
                        ToastUtils.ShowToast(mContext, "请输入提币地址");
                        return;
                    } else {
                        presenter.addAddress(app.getUserId(), bean.getCoinEunit(), address, remark);
                        builder.dismiss();
                    }
                }

                @Override
                public void onOk() {

                }
            });

            builder.setZxingClickListener(() -> reqPermission(new String[]{Manifest.permission.CAMERA}, () -> IntentUtil.toActivityForResult(CaptureActivity.class, this, REQUEST_CODE)));
        }
        builder.creater().show();
    }

    @OnClick(R.id.btn_commit)
    public void commitClick() {

        String numStr = editText.getText().toString();
        if (TextUtils.isEmpty(numStr)) {
            showToast("请输入提币金额");
            return;
        }
        double num ;
        try {
            num = Double.parseDouble(numStr);

            if (num <= 0 || num > Double.parseDouble(bean.getHotMoney())) {
                showToast("请输入有效金额");
                return;
            }

            String addr = tvAddr.getText().toString();
            if (TextUtils.isEmpty(addr)) {
                showToast("没有提币地址");
                return;
            }
            showVerifyCodeDialog(num,addr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private TextView getVerifyCodeTV;
    private void showVerifyCodeDialog(double num ,String addr) {
        mDialog = new MyCustomDialog.Builder(mContext, R.style.OrderDialogStyle);
        mDialog.setContent(app.getmData().getCenterUserMain().getPhone())
                .setTitle("手机验证")
                .setRightBtnStr("确定")
                .setOnGetVerifyCodeClick(new MyCustomDialog.OnGetVerifyCodeClick() {
                    @Override
                    public void onClickGetVerifyCode(TextView tv) {
                        presenter.getCode(app.getmData().getCenterUserMain().getPhone());
                        getVerifyCodeTV = tv;
                    }
                }).setOnBtnClickListener(new MyCustomDialog.OnButtonClick() {
            @Override
            public void onOk(String checkCode) {
                if (!TextUtils.isEmpty(checkCode) && checkCode.length() >= 4) {
                    mDialog.dismiss();
                    presenter.commit(app.getUserId(), bean.getCoinEunit(), num, addr ,checkCode);
                } else {
                    ToastUtils.ShowToast(mContext, "请输入正确的验证码");
                }
            }

            @Override
            public void onOk() {

            }

            @Override
            public void onCancel() {
                if (timer != null) {
                    timer.cancel();
                    getVerifyCodeTV = null;
                }
            }
        }).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (builder != null) {
                        builder.setZXingCode(result);
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
